package com.banciyuan.bcywebview.biz.main.daily;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.fragment.BaseContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.goods.order.myorder.MyOrderActivity;
import com.banciyuan.bcywebview.biz.goods.shoppingcart.ShoppingCartActivity;
import com.banciyuan.bcywebview.biz.goods.shoppingcart.ShoppingCartHelper;
import com.banciyuan.bcywebview.biz.goods.store.AllGoodsActivity;
import com.banciyuan.bcywebview.biz.goods.store.GoodsStoreAdapter;
import com.banciyuan.bcywebview.biz.goods.store.HotGoodsActivity;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.main.banner.ViewBanner;
import com.banciyuan.bcywebview.biz.search.SearchActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.DetailGoods;
import de.greenrobot.daoexample.model.DiscoverBanner;
import de.greenrobot.daoexample.model.GoodsChoice;
import de.greenrobot.daoexample.model.GoodsProduct;
import de.greenrobot.daoexample.model.GoodsWork;

public class DailyFragment extends BaseContainerFragment implements OnClickListener {

    public static final int TAG = 3;

    private PullToRefreshListView mRefresh;
    private ListView mListview;
    private View buy_car_num;
    private View login;
    private View buy_car;
    private FrameLayout goods_car;
    private LinearLayout goods_order;
    private LinearLayout goods_join;
    private LinearLayout search;
    private TextView checkall;
    private View all_goods;
    private ConvenientBanner page_banner;
    private View viewFooterContainer;
    private LinearLayout goodsProductsContainer;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    private List<GoodsChoice> mGoodsChoiceList = new ArrayList<>();
    private GoodsStoreAdapter goodsAdapter;
    private ImageView[] workGoodsPics;
    private TextView[] workNames;
    private TextView[] workGoodsCounts;
    private View[] hotworkViewContainers;
    private int page = 1;
    private boolean hasMore = true;
    private boolean loading = false;
    private List<GoodsProduct> goodsProducts;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.goods_store_activity, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initData();
        getBanner();
        getGoodsProducts();
        getHotWorks();
        initAction();
        return rootView;
    }

    @Override
    protected void initUi(View rootView) {
        mRefresh = (PullToRefreshListView) rootView.findViewById(R.id.list);
        mListview = mRefresh.getRefreshableView();
        buy_car_num = rootView.findViewById(R.id.buy_car_num);
        buy_car = rootView.findViewById(R.id.buy_car_iv);

        login = rootView.findViewById(R.id.view_login);
        goods_car = (FrameLayout) rootView.findViewById(R.id.goods_car);
        search = (LinearLayout) rootView.findViewById(R.id.search);

        View header = View.inflate(getActivity(), R.layout.goods_store_header, null);
        goods_order = (LinearLayout) header.findViewById(R.id.goods_order);
        goods_join = (LinearLayout) header.findViewById(R.id.goods_join);
        all_goods = header.findViewById(R.id.ranking_title_line);
        page_banner = (ConvenientBanner) header.findViewById(R.id.pager_banner);

        goodsProductsContainer = (LinearLayout) header.findViewById(R.id.goods_products_container);
        header.findViewById(R.id.all_goods_title).setOnClickListener(this);
        initHotGoodsView(header);

        View footer = View.inflate(getActivity(), R.layout.goods_store_footer, null);
        viewFooterContainer = footer.findViewById(R.id.view_footer_container);
        checkall = (TextView) footer.findViewById(R.id.footer_checkall);
        viewFooterContainer.setVisibility(View.GONE);

        mListview.addHeaderView(header);
        mListview.addFooterView(footer);

        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            buy_car.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);
        } else {
            buy_car.setVisibility(View.INVISIBLE);
            login.setVisibility(View.VISIBLE);
        }
    }

    private void initHotGoodsView(View header) {
        header.findViewById(R.id.view_goto_moregoods).setOnClickListener(this);
        View hotGoodsOne = header.findViewById(R.id.hotgoods_one);
        View hotGoodsTwo = header.findViewById(R.id.hotgoods_two);
        View hotGoodsThree = header.findViewById(R.id.hotgoods_three);
        View hotGoodsFour = header.findViewById(R.id.hotgoods_four);
        hotworkViewContainers = new View[]{hotGoodsOne, hotGoodsTwo, hotGoodsThree, hotGoodsFour};
        workGoodsPics = new ImageView[]{(ImageView) hotGoodsOne.findViewById(R.id.iv_goods_pic), (ImageView) hotGoodsTwo.findViewById(R.id.iv_goods_pic),
                (ImageView) hotGoodsThree.findViewById(R.id.iv_goods_pic), (ImageView) hotGoodsFour.findViewById(R.id.iv_goods_pic)};
        workNames = new TextView[]{(TextView) hotGoodsOne.findViewById(R.id.tv_work_name), (TextView) hotGoodsTwo.findViewById(R.id.tv_work_name),
                (TextView) hotGoodsThree.findViewById(R.id.tv_work_name), (TextView) hotGoodsFour.findViewById(R.id.tv_work_name)};
        workGoodsCounts = new TextView[]{(TextView) hotGoodsOne.findViewById(R.id.tv_goods_count), (TextView) hotGoodsTwo.findViewById(R.id.tv_goods_count),
                (TextView) hotGoodsThree.findViewById(R.id.tv_goods_count), (TextView) hotGoodsFour.findViewById(R.id.tv_goods_count)};
    }

    @Override
    protected void initAction() {
        goods_order.setOnClickListener(this);
        goods_join.setOnClickListener(this);
        checkall.setOnClickListener(this);
        all_goods.setOnClickListener(this);
        goods_car.setOnClickListener(this);
        search.setOnClickListener(this);
        login.setOnClickListener(this);

        mRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    loading = true;
                    hasMore = true;
                    page = 1;
                    viewFooterContainer.setVisibility(View.GONE);
                    initData();
                }
            }
        });
        mRefresh.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && hasMore) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initProgressbar(View rootView) {
        mProgressbarView = rootView.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    private void getBanner() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getIndexBanners();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<DiscoverBanner> dblist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<DiscoverBanner>>() {
                        }.getType());
                        renderBanner(dblist);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), null);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, null, onSucc, onErrorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    private void renderBanner(List<DiscoverBanner> dlist) {
        if (dlist.size() > 0) {
            page_banner.setVisibility(View.VISIBLE);
            page_banner.setPages(new CBViewHolderCreator() {
                @Override
                public Object createHolder() {
                    return new ViewBanner();
                }
            }, dlist)
                    .setPageIndicator(new int[]{R.drawable.shape_dot_unselected, R.drawable.shape_dot_selected});
        } else {
            page_banner.setVisibility(View.GONE);
        }
    }

    private void getGoodsProducts() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getListGoodsProducts();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        goodsProducts = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<GoodsProduct>>() {
                        }.getType());
                        dealGoodsProducts();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), null);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, null, onSucc, onErrorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    private void dealGoodsProducts() {
        goodsProductsContainer.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        if (goodsProducts == null || goodsProducts.isEmpty()) {
            goodsProductsContainer.setVisibility(View.GONE);
            return;
        }
        goodsProductsContainer.setVisibility(View.VISIBLE);
        for (int i = 0; i < goodsProducts.size(); i++) {
            LinearLayout viewLine = (LinearLayout) layoutInflater.inflate(R.layout.goods_store_products_item, goodsProductsContainer, false);
            setProductItem(viewLine, i);
            goodsProductsContainer.addView(viewLine);
        }

    }

    private void setProductItem(View viewProduct, int pos) {
        final GoodsProduct goodsProduct = goodsProducts.get(pos);
        ImageView ivProductCover = (ImageView) viewProduct.findViewById(R.id.iv_categorytag_cover);
        TextView tvProductName = (TextView) viewProduct.findViewById(R.id.tv_categorytag_name);
        ImageLoader.getInstance().displayImage(goodsProduct.getIcon(), ivProductCover, ImageOptions.options);
        tvProductName.setText(goodsProduct.getName());
        viewProduct.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(getActivity(), AllGoodsActivity.class, goodsProduct.getZp_id());
            }
        });
    }

    private void getHotWorks() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getIndexHotWorks();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<GoodsWork> goodsWorks = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<GoodsWork>>() {
                        }.getType());
                        dealGoodsWorks(goodsWorks);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), null);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, null, onSucc, onErrorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    private void dealGoodsWorks(List<GoodsWork> goodsWorks) {
        int size = goodsWorks.size() >= 4 ? 4 : goodsWorks.size();
        for (View viewContainer : hotworkViewContainers) {
            viewContainer.setVisibility(View.GONE);
        }
        for (int i = 0; i < size; i++) {
            final GoodsWork goodsWork = goodsWorks.get(i);
            hotworkViewContainers[i].setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(goodsWork.getCover(), workGoodsPics[i], ImageOptions.options);
            workNames[i].setText(Html.fromHtml(goodsWork.getReal_name()));
            workGoodsCounts[i].setText(String.format(getString(R.string.goods_category_format), goodsWork.getGoods_count()));
            hotworkViewContainers[i].setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), CircleSmoothActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, goodsWork.getReal_name());
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, goodsWork.getId());
                    intent.putExtra("from", 3);
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getGoodsChoic();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<GoodsChoice> dlist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<GoodsChoice>>() {
                        }.getType());
                        isDataEmpty(dlist);
                        popItem(dlist);
                        processGoodsChoice(dlist);
                        renderData();
                        onSuccess();
                    } else {
                        onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onError();
                } finally {
                    onError();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onError();
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), params);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, params, onSucc, onErrorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    private void isDataEmpty(List<GoodsChoice> dlist) {
        if (dlist.isEmpty()) {
            hasMore = false;
            viewFooterContainer.setVisibility(View.VISIBLE);
        }
    }

    private void onError() {
        loading = false;
        mProgressbarHelper.onSuccess();
        mRefresh.onRefreshComplete();
    }

    private void processGoodsChoice(List<GoodsChoice> tempGoodsChoice) {
        List<GoodsChoice> legalGoodsChoice = new ArrayList<>();
        for (int i = 0; i < tempGoodsChoice.size(); i++) {
            GoodsChoice goodsChoice = tempGoodsChoice.get(i);
            if (null == goodsChoice || null == goodsChoice.getData())
                continue;
            String type = goodsChoice.getType();
            if ("goods".equals(type)) {
                if (i + 1 < tempGoodsChoice.size()) {
                    GoodsChoice nextGoodsChoice = tempGoodsChoice.get(i + 1);
                    if (null != nextGoodsChoice && null != nextGoodsChoice.getData()) {
                        if ("goods".equals(nextGoodsChoice.getType())) {
                            goodsChoice.setNextGoodsData(nextGoodsChoice.getData());
                            legalGoodsChoice.add(goodsChoice);
                            i++;
                        }
                    }
                }
            } else if ("special".equals(type) || "work".equals(type)) {
                legalGoodsChoice.add(goodsChoice);
            }
        }
        if (page == 1) {
            mGoodsChoiceList.clear();
        }
        mGoodsChoiceList.addAll(legalGoodsChoice);
    }

    private void renderData() {
        if (goodsAdapter == null) {
            goodsAdapter = new GoodsStoreAdapter(mGoodsChoiceList, getActivity());
            mListview.setAdapter(goodsAdapter);
        } else {
            goodsAdapter.notifyDataSetChanged();
        }
    }

    private void onSuccess() {
        loading = false;
        mRefresh.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }


    private void readCar() {
        List<DetailGoods> dlist = ShoppingCartHelper.getShoppingItems(getActivity());
        if (dlist.isEmpty()) {
            buy_car_num.setVisibility(View.GONE);
        } else {
            buy_car_num.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goods_order:
                gotoUtil.gotoAct(getActivity(), MyOrderActivity.class);
                break;
            case R.id.goods_join:
                DetailDataHelper.gotoDailyDetail(getActivity(), "405463", false);
                break;
            case R.id.ranking_title_line:
            case R.id.footer_checkall:
            case R.id.all_goods_title:
                gotoUtil.gotoAct(getActivity(), AllGoodsActivity.class);
                break;
            case R.id.goods_car:
                gotoUtil.gotoAct(getActivity(), ShoppingCartActivity.class);
                break;
            case R.id.search:
                gotoUtil.gotoAct(getActivity(), SearchActivity.class, "goods");
                break;
            case R.id.view_goto_moregoods:
                gotoUtil.gotoAct(getActivity(), HotGoodsActivity.class);
                break;
            case R.id.view_login:
                gotoUtil.gotoAct(getActivity(), LoginActivity.class);
                break;
        }
    }

    private void popItem(List<GoodsChoice> dlist) {
        List<GoodsChoice> result = new ArrayList<>();
        for (GoodsChoice d : dlist) {
            try {
                if ("goods".equals(d.getType()) && StringUtil.notNullEqual(d.getData().getZg_id(), "0")) {
                    result.add(d);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        dlist.removeAll(result);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (null != page_banner) {
            page_banner.startTurning(3000);
        }
        readCar();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != page_banner) {
            page_banner.stopTurning();
        }
    }

    @Override
    public void selfUpdateData() {
        mRefresh.setRefreshing();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    }
}